package cn.myblog.ainblog.conroller.backstage;

import cn.myblog.ainblog.service.UserService;
import com.sun.mail.smtp.DigestMD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Dovaior
 * @Description 登录的控制器
 * @create 2021-04-11 15:29
 **/
@Controller
@RequestMapping("/Admin")
public class BackstageLoginController {
    @Autowired
    private UserService service;

    /**
     * 登录
     * @param userName 从前端获取的username
     * @param password 从前端获取的password
     * @param session 将登录信息存入session
     * @param model 封装信息
     * @return 返回页面
     */
    @PostMapping("/login")
    public String login(@RequestParam("username") String userName, @RequestParam("password") String password, HttpSession session, Model model) {
        //错误提示
        String msg = "";
        //跳转页面
        String direction = "backstage/backstage-login";
        String md5Username = DigestUtils.md5DigestAsHex(userName.getBytes());
//        System.out.println("加密昵称："+md5Username);
        String queryMd5Password = service.selectPasswordByUsername(md5Username);
//        System.out.println("查询出来的密码："+queryMd5Password);
        //当没有查询出密码，说明该用户名错误
        if (queryMd5Password == null) {
            msg = "用户名不存在！";
        }else {
            //查询出密码后，将输入的密码加密
            String Md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
            //用输入的密码和查询出的密码比对，当查询出来的密码与获取的密码不相等，说明密码输入错误
            if (!(Md5Password.equals(queryMd5Password))){
                //密码不正确
                msg = "密码错误！";
            }else {
                //密码正确
                //将加密id存起来用于主要查询
                session.setAttribute("LoginUser",md5Username);
                //将输入值存起来用于显示
                session.setAttribute("username",userName);
                session.setAttribute("password",password);
                direction = "redirect:/backstage/index";
            }
        }
        model.addAttribute("msg",msg);
        return direction;
    }

    /**
     * 登出
     * @param session 清空session
     * @return 返回提示信息
     */
    @ResponseBody
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "退出成功";
    }
}
